package com.jinxixin.android.recordvideo;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;

import com.jinxixin.android.recordvideo.bean.MessageEvent;
import com.jinxixin.android.recordvideo.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class RecordVideoFinishActivity extends AppCompatActivity {
    private static final String TAG = "RecordVideoFinishAc";
    private Context mContext;
    private VideoView videoView;
    private TextView tv_back;
    private TextView tv_confirm;
    private SeekBar seekBar;
    private ImageView img_play;
    private TextView tv_time;

    public static void launch(Context context, String filePath) {
        Intent intent = new Intent(context, RecordVideoFinishActivity.class);
        intent.putExtra("data", filePath);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_video_finish);
        mContext = this;
        initView();
        initData();
        initListener();
    }

    private void initView() {
        videoView = findViewById(R.id.videoView);
        seekBar = findViewById(R.id.seekBar);
        tv_time = findViewById(R.id.tv_time);
        img_play = findViewById(R.id.img_play);
        tv_back = findViewById(R.id.tv_back);
        tv_confirm = findViewById(R.id.tv_confirm);
        setupVideo();
    }

    private void initData() {

    }

    private void initListener() {
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MessageEvent messageEvent = new MessageEvent(MessageEvent.FINISH_RECORD_VIDEO);
                messageEvent.setData(mFilePath);
                EventBus.getDefault().post(messageEvent);
            }
        });
        img_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoView.isPlaying()) {
                    videoView.pause();
                    img_play.setImageResource(R.drawable.ic_play_video);
                } else {
                    img_play.setImageResource(R.drawable.ic_pause_video);
                    //videoView.seekTo(0);
                    videoView.start();
                }
            }
        });
    }

    private String mFilePath;

    private void setupVideo() {
        mFilePath = getIntent().getStringExtra("data");
        //mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.mp4";
        videoView.setVideoPath(mFilePath);//设置视频文件
        //将路径转换成uri
        //Uri uri = Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
        //为视频播放器设置视频路径
        //videoView.setVideoURI(uri);

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //Toast.makeText(mContext, "播放完成", Toast.LENGTH_SHORT).show();
                seekBar.setProgress(seekBar.getMax());
                tv_time.setText(TimeUtils.formatLongToTimeStr(videoView.getDuration()) + "/" + TimeUtils.formatLongToTimeStr(videoView.getDuration()));
            }
        });

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                seekBar.setMax(videoView.getDuration());

                tv_time.setText(TimeUtils.formatLongToTimeStr(videoView.getCurrentPosition()) + "/" + TimeUtils.formatLongToTimeStr(videoView.getDuration()));

                videoView.start();
                img_play.setImageResource(R.drawable.ic_pause_video);

                mHandler.postDelayed(mRunnable, 0);
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //停止播放
                videoView.pause();
                img_play.setImageResource(R.drawable.ic_play_video);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                tv_time.setText(TimeUtils.formatLongToTimeStr(progress) + "/" + TimeUtils.formatLongToTimeStr(videoView.getDuration()));
                //设置当前播放的位置
                videoView.seekTo(progress);
                //继续播放
                videoView.start();
                img_play.setImageResource(R.drawable.ic_pause_video);
            }
        });
    }

    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        public void run() {
            if (videoView.isPlaying()) {
                int current = videoView.getCurrentPosition();
                seekBar.setProgress(current);
                tv_time.setText(TimeUtils.formatLongToTimeStr(current) + "/" + TimeUtils.formatLongToTimeStr(videoView.getDuration()));
            }
            mHandler.postDelayed(mRunnable, 500);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getMsgCode() == MessageEvent.FINISH_RECORD_VIDEO) {
            finish();
        } else if (event.getMsgCode() == MessageEvent.FINISH_TAKE_PICTURE) {
            finish();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacks(mRunnable);

        //取消注册EventBus
        if (EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
